﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Configuration;
using Microsoft.Practices.EnterpriseLibrary.Data;
using Enter.DataCommon;

namespace Enter.DataProxy.DbConnector.Helpers
{
    /// <summary>
    /// 针对企业库环境信息的实现。
    /// </summary>
    internal class DatabaseHelper : DbHelper
    {
        /// <summary>
        /// 配置文件中数据链接字符串的组名称(ConnectionsGroup)，依赖企业库的配置文件。
        /// </summary>
        /// <remarks>企业库创建Database对象需要Connections中的连接名称，因为DataProxy需要提供DB链接负载均衡的能力。name指向了一组链接字符串。</remarks>
        private string _Name;

        //private Pools<string> _Connections;

        private bool _IsSqlServer;

       // private SqlBuilder _default;

        /// <summary>
        /// 初始化
        /// </summary>
        /// <param name="name">配置文件中数据链接字符串的组名称，依赖企业库的配置文件。</param>
        public DatabaseHelper(string name)
        {
            _Name = name;
           // _Connections = ConnectionStringSettings.ConnectionGroup(name);
            var connSettings = Configuration.ConnectionsConfigManager.ConnectionSettings(_Name);
            switch (connSettings.ProviderName)
            {
                case "System.Data.SqlClient":
                    //_default = new SqlBuilder(new SqlBuilder.SqlCharacter());
                    _IsSqlServer = true;
                    break;
                case "System.Data.OracleClient":
                   // _default = new SqlBuilder(new SqlBuilder.OracleCharacter());
                    _IsSqlServer = false;
                    break;
                default:
                    //_default = SqlBuilder.Default;
                    _IsSqlServer = true;
                    break;
            }
        }


        public override ParameterCollection CreateParamCollection()
        {
            if (_IsSqlServer)
                return new SqlParameterCollection();
            else
                return new OracleParameterCollection();
        }

        public override ParameterCollection CreateParamCollection(int capacity)
        {
            if (_IsSqlServer)
                return new SqlParameterCollection(capacity);
            else
                return new OracleParameterCollection(capacity);
        }

        protected internal override DataSet ExecuteDataSet(CommandType cmdType, string cmdText, ParameterCollection parameters)
        {
            var db = CreateDatabase();
            return db.ExecuteDataSet(cmdType, cmdText, parameters);
        }

        protected internal override int ExecuteNonQuery(CommandType cmdType, string cmdText, ParameterCollection parameters, bool mustTransaction)
        {
            var db = CreateDatabase();
            if (mustTransaction)
            {
                return db.ExecuteNonQuery(cmdType, cmdText, parameters);
            }
            else
            {
                using (var conn = db.CreateConnection())
                {
                    conn.Open();
                    using (var tran = conn.BeginTransaction())
                    {
                        int val = db.ExecuteNonQuery(cmdType, cmdText, parameters, tran);
                        tran.Commit();
                        return val;
                    }
                }
            }
        }

        protected internal override IDataReader ExecuteReader(CommandType cmdType, string cmdText, ParameterCollection parameters)
        {
            var db = CreateDatabase();
            return db.ExecuteReader(cmdType, cmdText, parameters);
        }

        protected internal override object ExecuteScalar(CommandType cmdType, string cmdText, ParameterCollection parameters, bool mustTransaction)
        {
            var db = CreateDatabase();
            if (mustTransaction)
            {
                return db.ExecuteScalar(cmdType, cmdText, parameters);
            }
            else
            {
                using (var conn = db.CreateConnection())
                {
                    conn.Open();
                    using (var tran = conn.BeginTransaction())
                    {
                        object val = db.ExecuteScalar(cmdType, cmdText, parameters, tran);
                        tran.Commit();
                        return val;
                    }
                }
            }
        }

		private string SqlPageSqlServer = @"select count(1) {0};
								select * from (
								SELECT ROW_NUMBER() OVER(ORDER BY {1}) AS _ROWID,
								{2} ) as _tab
								where _rowid>@minid and _rowid<=@maxid
								order by _tab._ROWID ;";

		protected override DataPageSql ExecutePageSqlTxt(string commandText, ParameterCollection parameters)
		{
			DataPageSql result = base.ExecutePageSqlTxt(commandText,parameters);
			if (result.IsSuccess)
			{
				if (_IsSqlServer)
				{
					commandText = commandText.Replace(";", "");
					string sqltxt = string.Empty;
					int comandsize = commandText.Length;
					int size = commandText.ToLower().IndexOf(" from");
					string sqlselect = commandText.Substring(7);
					result.PageSql = string.Format(SqlPageSqlServer, commandText.Substring(size), result.order, sqlselect);
					result.parameters = CreateParamCollection(2);
					result.parameters.Append("minid", (result.pageid - 1) * result.pagesize);
					result.parameters.Append("maxid", result.pageid * result.pagesize);
				}
				else
				{ 
					
				}
			}
			return result;
		}

				/// <summary>
		/// sql 自动分页程序
		/// </summary>
		/// <param name="commandText"></param>
		/// <param name="parameters"></param>
		/// <returns></returns>
		public override DataPage ExecutePage(string commandText, ParameterCollection parameters)
		{
			return base.ExecutePage(commandText, parameters);
		}
        /// <summary>
        /// 创建一个Database对象。
        /// </summary>
        /// <returns></returns>
        public Database CreateDatabase()
        {
            return DatabaseFactory.CreateDatabase(_Name);
        }
    }
}
